package com.crp.unitalinforbaseplat.app.sys.controller;

import com.crp.unitalinforbaseplat.app.core.Message;
import com.crp.unitalinforbaseplat.app.core.MessageUtil;
import com.crp.unitalinforbaseplat.app.core.utils.MD5Util;
import com.crp.unitalinforbaseplat.app.sys.entity.User;
import com.crp.unitalinforbaseplat.app.sys.service.UserService;
import com.crp.unitalinforbaseplat.app.unitalinforbaseplat.entity.Principal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/unitlinforbase/")
public class LoginController {
    @Autowired
    UserService userService;

    Logger logger = LoggerFactory.getLogger("LoginController");
    @RequestMapping(value = "/index.crp",method = RequestMethod.GET)
    ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("backend/login");
        modelAndView.addObject("title", "汽车零配件管理系统");
        modelAndView.addObject("index", "");
        return modelAndView;
    }

    @RequestMapping("/login/verify.crp")
    @ResponseBody
    Message verfy(User user) {
        user.setPassword(MD5Util.Companion.getMD5String(user.getUsername(), user.getPassword()));
        logger.info(user.getPassword());
        try {
            UsernamePasswordToken token = new  UsernamePasswordToken(user.getUsername(), user.getPassword());
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return MessageUtil.createMessage(false, "账号密码不正确");
        }
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal() ;
        return MessageUtil.createMessage(true, "登录成功");
    }

    @RequestMapping(value = "/register_index")
    ModelAndView register_index(){
        ModelAndView modelAndView = new ModelAndView("backend/register");
        modelAndView.addObject("title", "账号注册");
        return modelAndView;
    }


}
